#include "flash.h"

static uint16_t STMFLASH_GetFlashSector(u32 addr);

const uint32_t Flash_SectorSize[12] = \
{
  FLASH_Sector_0,
  FLASH_Sector_1,
  FLASH_Sector_2,
  FLASH_Sector_3,
  FLASH_Sector_4,
  FLASH_Sector_5,
  FLASH_Sector_6,
  FLASH_Sector_7,
  FLASH_Sector_8,
  FLASH_Sector_9,
  FLASH_Sector_10,
  FLASH_Sector_11
};


static void Flash_Unlock(void)
{
  FLASH_Unlock();
  while(FLASH_GetStatus() == FLASH_BUSY);
}

static void Flash_lock(void)
{
  FLASH_Lock();
}

/**
  * @brief Erase sector
  * @param FLASH_Sector: Need be eraseed sector.
  */
FLASH_Status FlashAppSector(uint32_t FLASH_Sector)
{
  Flash_Unlock();
  FLASH_Status flash_status =  FLASH_EraseSector(FLASH_Sector, VoltageRange_3);
  Flash_lock();
  return flash_status;
}

void flash_write(uint32_t address, uint32_t data)
{
  Flash_Unlock();
  FLASH_Status status = FLASH_ProgramWord(address, data);
  
  if (status == FLASH_COMPLETE)
  {
    /* Flash write successful */
  }
  else
  {
    /* Flash write failed */
  }
  
  Flash_lock();
}

/**
  * @brief Get sector by address.
  */
static uint16_t STMFLASH_GetFlashSector(u32 addr)
{
	if(addr<ADDR_FLASH_SECTOR_1)return FLASH_Sector_0;
	else if(addr<ADDR_FLASH_SECTOR_2)return FLASH_Sector_1;
	else if(addr<ADDR_FLASH_SECTOR_3)return FLASH_Sector_2;
	else if(addr<ADDR_FLASH_SECTOR_4)return FLASH_Sector_3;
	else if(addr<ADDR_FLASH_SECTOR_5)return FLASH_Sector_4;
	else if(addr<ADDR_FLASH_SECTOR_6)return FLASH_Sector_5;
	else if(addr<ADDR_FLASH_SECTOR_7)return FLASH_Sector_6;
	else if(addr<ADDR_FLASH_SECTOR_8)return FLASH_Sector_7;
	else if(addr<ADDR_FLASH_SECTOR_9)return FLASH_Sector_8;
	else if(addr<ADDR_FLASH_SECTOR_10)return FLASH_Sector_9;
	else if(addr<ADDR_FLASH_SECTOR_11)return FLASH_Sector_10; 
	return FLASH_Sector_11;	
}

/**
  * @brief Erase sector by addr
  * @param addr
  *        size
  * @retval 1:success
  *         0:failed  
  */
uint8_t Flash_erase(u32 addr, u32 size)
{
  uint32_t flash_start_sector = 0;
  uint32_t flash_end_sector = 0;
  flash_start_sector = STMFLASH_GetFlashSector(addr);
  flash_end_sector = STMFLASH_GetFlashSector(addr + size);
  
  for (uint8_t i = 0; i <= 12; i++)
  {
    if ((Flash_SectorSize[i] >= flash_start_sector) && (Flash_SectorSize[i] <= flash_end_sector))
    {
      if (FLASH_COMPLETE != FlashAppSector(Flash_SectorSize[i])) return 1;
    }
  }
  
  return 0;
}